/*
 * @Author: maskMan
 * @LastEditTime: 2023-05-04 19:07:35
 * @Descripttion:节点池管理
 */

export default class poolManager {
  static _dictPool: { [name: string]: cc.NodePool } = {}
  static _dictPrefab: { [name: string]: cc.Prefab } = {}
  /**
   * 初始化创建一些预支体放入池内
   * @param {cc.Prefab} prefab 创建的预制体
   * @param {number} ctrol 仓位控制数量
   */
  static init(prefab: cc.Prefab, ctrol?: number): void {
    ctrol = ctrol || 10
    const name = prefab.data.name
    let pool = null
    if (this._dictPool[name]) {
      //已有对应的对象池
      pool = this._dictPool[name]
    } else {
      //没有对应对象池，创建他！
      pool = new cc.NodePool()
      this._dictPool[name] = pool
    }
    const count = pool.size() - ctrol
    if (count < 0) {
      for (let i = 0; i < count; i++) {
        pool.put(cc.instantiate(prefab))
      }
    }
  }
  /**
   * @description: 从池获取节点对象
   * @param {cc} prefab 预制体
   * @return {cc.Node} 节点
   */
  static getNode(prefab: cc.Prefab): cc.Node {
    const name = prefab.data.name
    this._dictPrefab[name] = prefab
    let node: cc.Node
    if (this._dictPool[name]) {
      //已有对应的对象池
      const pool = this._dictPool[name]
      if (pool.size() > 0) {
        node = pool.get()
      } else {
        node = cc.instantiate(prefab)
      }
    } else {
      //没有对应对象池，创建他！
      const pool = new cc.NodePool()
      this._dictPool[name] = pool
      node = cc.instantiate(prefab)
      pool.put(node)
      node = pool.get()
    }
    return node
  }
  /**
   * @description: 将节点放回对象池
   * @param {cc.Node} node
   * @return {void}
   */
  static putNode(node: cc.Node): void {
    const name = node.name
    let pool = null
    if (this._dictPool[name]) {
      //已有对应的对象池
      pool = this._dictPool[name]
    } else {
      //没有对应对象池，创建他！
      pool = new cc.NodePool()
      this._dictPool[name] = pool
    }
    pool.put(node)
  }
  /**
   * @description: 清理对象池
   * @param {string} name
   * @return {void}
   */
  static clearPool(name?: string): void {
    if (name) {
      if (this._dictPool[name]) {
        const pool = this._dictPool[name]
        pool.clear()
      }
    } else {
      for (const key in this._dictPool) {
        if (this._dictPool[key]) {
          const pool = this._dictPool[name]
          pool.clear()
        }
      }
    }
  }
}
